package com.welike.shibo.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import com.welike.shibo.enums.ResultEnum;
import com.welike.shibo.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONException;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 发送邮件工具类
 *
 * @author fangyu
 * @version v1.0.0
 * @since 2019-08-19 19:18
 */
@Slf4j
@Component("smsUtils")
public class SmsUtils {

    /**
     * 阿里云短信发送的公共部分封装
     *
     * @return
     * @throws ClientException
     * @Classname SmsService
     */
    private IAcsClient sendMsgCommon() throws ClientException {
        //HttpURLConnection是基于HTTP协议的，其底层通过socket通信实现。
        // 如果不设置超时（timeout），在网络异常的情况下，可能会导致程序僵死而不继续往下执行。可以通过以下两个语句来设置相应的超时：
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", Constants.TIMEOUT_LIMIT);
        System.setProperty("sun.net.client.defaultReadTimeout", Constants.TIMEOUT_LIMIT);

        //  初始化acsClient，暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", Constants.ACCESSSKEY_ID, Constants.ACCESSKEY_SECRET);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", Constants.PRODUCT, Constants.DOMAIN);
        return new DefaultAcsClient(profile);
    }

    /**
     * 阿里云发送短信
     *
     * @param phone 手机号
     * @param code  验证码
     * @throws ClientException
     */
    public void sendSmsForLogin(String phone, int code) throws ClientException {
        // 手机号码的非空判断
        if (phone == null || phone.equals("")) {
            throw new BaseException(ResultEnum.PHONE_DONT_NOT_NULL);
        }
        IAcsClient iAcsClient = sendMsgCommon();
        // 组装请求对象
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(Constants.DOMAIN);
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", Constants.SIGN_NAME); //
        request.putQueryParameter("TemplateCode", Constants.TEMPLATE_YZ_LOGIN); // 短信模板
        request.putQueryParameter("TemplateParam", "{\"code\":" + code + "}");  // 验证码code
        try {
            CommonResponse response = iAcsClient.getCommonResponse(request);
            log.info("status: {}, data: {}, response: {}", response.getHttpStatus(), response.getData(), response.getHttpResponse());
        } catch (ClientException e) {
            log.error("error: {}", e.getMessage());
        }
    }

    private SmsSingleSender txSmsClient() {
        return new SmsSingleSender(Constants.TX_APP_ID, Constants.TX_APP_KEY);
    }

    /**
     * 腾讯云发送短信
     *
     * @param phone 手机号
     * @param code  验证码
     */
    public void txSendSms(String phone, int code, String minutes, int templateId) throws HTTPException {
        String[] param = new String[2];
        param[0] = String.valueOf(code);
        param[1] = minutes;
        // 手机号码的非空判断
        if (phone == null || phone.equals("")) {
            throw new BaseException(ResultEnum.PHONE_DONT_NOT_NULL);
        }
        try {
            SmsSingleSender txSmsClient = txSmsClient();
            SmsSingleSenderResult result = txSmsClient.sendWithParam("86", phone, templateId, param, Constants.TX_SIGN, "", "");
            log.info("result: {}", result);
        } catch (HTTPException | JSONException | IOException e) {
            log.error("error: {}", e.getMessage());
        }
    }
}
